package services.gyerpapi

import javax.inject.{Inject, Singleton}
import play.api.libs.json.{JsObject, Json, __}
import play.api.{Configuration, Logging}
import play.api.libs.ws.WSClient
import security.Encode

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

@Singleton
class GYCErpPost @Inject()(
                            ws: WSClient,
                            config: Configuration
                          )(implicit exec: ExecutionContext)
  extends Logging {

  val gyConfig = config.get[GYCErpConfig]("")

  val sec = security.Encode

  def sign(data: String) = {
    sec.hashMD5(gyConfig.secret + data + gyConfig.secret).toUpperCase
  }

  def post(obj: JsObject) = {
    val json = Json.obj(
      "appkey" -> gyConfig.appkey,
      "sessionkey" -> gyConfig.sessionkey
    )
    val add = __.json.update(__.read[JsObject].map { o => o ++ obj })
    val data = json.transform(add).map(res => {
      logger.debug(res.toString)
      res.toString()
      val add2 = __.json.update(
        __.read[JsObject].map { o =>
          o ++ Json.obj("sign" -> sign(res.toString))
        }
      )
      res.transform(add2).map(d => d)
    }).get.get
    logger.debug(data.toString)
    val res = ws.url(gyConfig.url)
      .addHttpHeaders("Content-Type" -> "application/json")
      .withRequestTimeout(300.second)
      .post(data)
    res.map(r => try {
      if (r.contentType.indexOf("json") > 0) r.json else Json.parse(r.body)
    } catch {
      case exception: Exception => {
        logger.info("gy.post exception", exception)
        Json.obj(
          "success" -> false,
          "errorCode" -> "",
          "subErrorCode" -> "",
          "errorDesc" -> "",
          "subErrorDesc" -> "",
          "total" -> 0)
      }
    }
    )
  }


}
